package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.College;
import com.EAsystem.entity.Major;
import com.EAsystem.service.CollegeService;
import com.EAsystem.service.MajorService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class MajorController {

    @Autowired
    private MajorService majorService;

    @Autowired
    private CollegeService collegeService;

    @GetMapping("/major")
    public String listMajor(@RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "5") int size,
                            Model model,
                            @RequestParam(required = false) String nameSearch) {
        try {
            PageInfo<Major> pageInfo;
            Major major = new Major();
            if (nameSearch != null && !nameSearch.trim().isEmpty()) {
                major.setName(nameSearch.trim());
                pageInfo = majorService.findByNamePage(major, page, size);
            } else {
                pageInfo = majorService.findAllByPage(page, size);
            }
            if (pageInfo == null) pageInfo = new PageInfo<>();

            // 获取所有学院信息，用于新增/编辑模态框的下拉选择
            PageInfo<College> collegePageInfo = collegeService.findAllByPage(1, 1000);
            model.addAttribute("colleges", collegePageInfo.getList());

            model.addAttribute("majors", pageInfo.getList());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("nameSearch", nameSearch);
            
        } catch (Exception e) {
            System.err.println("专业查询异常: " + e.getMessage());
            e.printStackTrace();
            
            // 设置错误时的默认值
            model.addAttribute("majors", new java.util.ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("nameSearch", nameSearch);
            model.addAttribute("error", "查询专业信息失败：" + e.getMessage());
        }
        
        return "admin/major";
    }

    @PostMapping("/major/add")
    public String addMajor(Major major, @RequestParam("collegeId") Integer collegeId) {
        // 设置学院信息
        if (collegeId != null) {
            College college = new College();
            college.setId(collegeId);
            major.setCollege(college);
        }
        
        // 设置时间
        String now = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
        major.setCreateTime(now);
        major.setUpdateTime(now);
        
        majorService.save(major);
        return "redirect:/admin/major";
    }

    @PostMapping("/major/edit")
    public String editMajor(Major major, @RequestParam("collegeId") Integer collegeId) {
        // 设置学院信息
        if (collegeId != null) {
            College college = new College();
            college.setId(collegeId);
            major.setCollege(college);
        }
        
        // 设置更新时间
        String now = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
        major.setUpdateTime(now);
        
        majorService.edit(major);
        return "redirect:/admin/major";
    }

    @GetMapping("/major/delete/{id}")
    public String deleteMajor(@PathVariable Integer id) {
        majorService.delete(id);
        return "redirect:/admin/major";
    }

    @GetMapping("/major/batchDelete")
    public String batchDelete(@RequestParam("ids") String ids) {
        List<Integer> idList = new ArrayList<>();
        for (String id : ids.split(",")) {
            idList.add(Integer.valueOf(id));
        }
        majorService.batchDelete(idList);
        return "redirect:/admin/major";
    }

    @GetMapping("/major/view/{id}")
    @ResponseBody
    public java.util.Map<String, Object> viewMajor(@PathVariable Integer id) {
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        try {
            Major major = majorService.findById(id);
            if (major != null) {
                result.put("success", true);
                result.put("major", major);
            } else {
                result.put("success", false);
                result.put("message", "专业不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取专业信息失败：" + e.getMessage());
        }
        return result;
    }
}